package com.hx.tx.springboot.aop;

import com.hx.tx.springboot.util.TransactionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @author jxlgcmh
 * @date 2020-05-18 01:10
 * @description
 */
@Component
@Aspect
@Scope("prototype")
public class TxAop2 {
    @Autowired
    private TransactionUtils transactionUtils;

    @Around("execution(public * com.hx.tx.springboot.service..*.*(..)) )")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //不要try catch 不然回滚不了，一直占用资源
        System.out.println("开启事务");
        TransactionStatus transactionStatus = transactionUtils.begin();
        proceedingJoinPoint.proceed();
        transactionUtils.commit(transactionStatus);
        System.out.println("提交事务");
    }


    @AfterThrowing("execution (* com.hx.tx.springboot.service..*.*(..)) )")
    public void afterThrowing() {
        System.out.println("事务开始回滚");
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
}
